<template>
  <div>
    <el-card style="margin-bottom: 10px">
      <CategorySelector :isShowAttrList="isShowAttrList"></CategorySelector>
    </el-card>
    <el-card v-if="!isShowAttrList">
      <vxe-button
        style="margin-bottom: 10px"
        status="primary"
        icon="vxe-icon-add"
        :disabled="!categoryStore.category3Id"
        @click="showAdd"
        v-has="'btn.Attr.add'"
        >添加属性值</vxe-button
      >
      <vxe-table
        border
        align="center"
        :row-config="{ isHover: true }"
        :data="attrList"
      >
        <vxe-column type="seq" title="序号" width="60"></vxe-column>
        <vxe-column width="150" field="attrName" title="属性名称"></vxe-column>
        <vxe-column title="属性值列表" align="left">
          <template #default="{ row }">
            <el-tag
              style="margin-right: 5px"
              v-for="item in row.attrValueList"
              :key="item.id"
              >{{ item.valueName }}</el-tag
            >
          </template>
        </vxe-column>
        <vxe-column width="150" title="操作">
          <template #default="{ row }">
            <vxe-button
              status="primary"
              icon="vxe-icon-edit"
              size="small"
              @click="showUpdate(row)"
              v-has="'btn.Attr.update'"
            ></vxe-button>
            <el-popconfirm
              :title="`确认删除${row.attrName}吗？`"
              @confirm="remove(row.id)"
            >
              <template #reference>
                <vxe-button
                  status="danger"
                  icon="vxe-icon-delete-fill"
                  size="small"
                  v-has="'btn.Attr.remove'"
                ></vxe-button>
              </template>
            </el-popconfirm>
          </template>
        </vxe-column>
      </vxe-table>
    </el-card>
    <el-card v-else style="margin-top: 20px">
      <span>属性名</span>
      <vxe-input
        v-model="attr.attrName"
        style="width: 200px; margin-left: 10px"
        placeholder="请输入属性名"
      ></vxe-input>
      <br />
      <div style="margin-top: 20px; margin-bottom: 20px">
        <vxe-button
          status="primary"
          icon="vxe-icon-add"
          :disabled="!attr.attrName"
          @click="addValue"
          >添加属性值</vxe-button
        >
        <vxe-button @click="isShowAttrList = false">取消</vxe-button>
      </div>
      <vxe-table :data="attr.attrValueList" border="inner" :show-header="false">
        <vxe-column type="seq" title="序号" width="60"></vxe-column>
        <vxe-column title="属性值名称">
          <template v-slot="{ row, $rowIndex }">
            <el-input
              type="text"
              v-model="row.valueName"
              :ref="(el: any) => inputsRef[$rowIndex] = el"
              v-if="row.isShowEdit"
              @blur="showSpan(row, $rowIndex)"
            />
            <span
              v-else
              @click="showInput(row, $rowIndex)"
              style="display: inline-block; width: 100%"
            >
              {{ row.valueName }}
            </span>
          </template>
        </vxe-column>
        <vxe-column width="80" title="操作" align="center">
          <template v-slot="{ row, $index }">
            <el-popconfirm
              :title="`确认删除${row.valueName}`"
              @confirm="() => attr.attrValueList.splice($index, 1)"
            >
              <template #reference>
                <vxe-button
                  status="danger"
                  icon="vxe-icon-delete-fill"
                  size="small"
                ></vxe-button>
              </template>
            </el-popconfirm>
          </template>
        </vxe-column>
      </vxe-table>
      <div style="margin-top: 20px">
        <vxe-button status="primary" @click="save" :disabled="isSaveDisabled"
          >保存</vxe-button
        >
        <vxe-button @click="isShowAttrList = false">取消</vxe-button>
      </div>
    </el-card>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref, watch, computed, nextTick } from "vue";
import { useCategoryStore } from "@/stores/category";
import {
  getAttrListApi,
  addOrUpdateAttrApi,
  deleteAttrApi,
} from "@/api/product/attr";
import { ElMessage } from "element-plus";
import { } from "element-plus";
import type { AttrListModel, AttrModel, AttrValueModel } from "@/types/index";
import { cloneDeep } from "lodash";
const categoryStore = useCategoryStore();
const attrList = ref<AttrListModel>([]);
const loading = ref(false);
const isShowAttrList = ref(false); // 控制是否显示属性列表
// 获取单个商品属性信息
const attr = reactive<AttrModel>({
  attrName: "",
  attrValueList: [],
  categoryId: -1,
  categoryLevel: 3,
});
// 获取属性管理列表
const getAttrList = async () => {
  loading.value = true;
  attrList.value = await getAttrListApi({
    category1Id: categoryStore.category1Id as number,
    category2Id: categoryStore.category2Id as number,
    category3Id: categoryStore.category3Id as number,
  });
  loading.value = false;
};
// 监控是否获取到属性列表
watch(
  () => categoryStore.category3Id,
  async (category3Id) => {
    if (category3Id) {
      getAttrList();
    } else {
      attrList.value = [];
      return;
    }
  }
);
const inputsRef = ref<any[]>([]);
// 添加一个属性值
const addValue = async () => {
  // 响应式数据的修改，响应式数据产生了变化以后DOM要不要重绘？要！要不要时间？要！
  attr.attrValueList.push({
    valueName: "",
    attrId: undefined, // 是属性的id
    isShowEdit: true,
  });

  await nextTick();
  console.log(inputsRef.value);
  // 现在attrValueList的长度-1获取的是最后一个元素，但是现在打出来的是undefined
  inputsRef.value[attr.attrValueList.length - 1].focus();
};
// 添加一个商品属性
const save = async () => {
  attr.categoryId = categoryStore.category3Id as number;
  attr.attrValueList = attr.attrValueList.filter((value) => {
    if (value.valueName) {
      return true;
    } else {
      return false;
    }
  });
  await addOrUpdateAttrApi(attr);
  ElMessage.success("保存成功");
  // 返回列表
  isShowAttrList.value = false;
  // 重新获取列表
  getAttrList();
};
// 判断是否能够进行属性添加
const isSaveDisabled = computed(() => {
  const { attrName, attrValueList } = attr;
  const hasName = !!attrName;
  const hasValue = attrValueList.some((value) => !!value.valueName);
  return !(hasName && hasValue);
});
// 清空表单数据
const showAdd = () => {
  Object.assign(attr, {
    attrName: "",
    attrValueList: [],
    categoryId: -1,
    categoryLevel: 3,
  });
  isShowAttrList.value = true;
};
// 点击修改属性
const showUpdate = (row: AttrModel) => {
  Object.assign(attr, cloneDeep(row));
  isShowAttrList.value = true;
};
// 删除属性值列表
const remove = async (id: number) => {
  await deleteAttrApi(id);
  ElMessage.success("删除成功");
  getAttrList();
};
const showInput = async (row: AttrValueModel, index: number) => {
  row.isShowEdit = true;
  await nextTick();
  inputsRef.value[index].focus();
};

const showSpan = (row: AttrValueModel, index: number) => {
  if (!row.valueName) {
    attr.attrValueList.splice(index, 1);
    return;
  }
  row.isShowEdit = false;
};
</script>
<script lang="ts">
export default {
  name: "Attr",
};
</script>
